<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>pgmpy.estimators.BayesianEstimator &#8212; pgmpy 0.1.2 documentation</title>
    
    <link rel="stylesheet" href="../../../_static/sphinxdoc.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../../',
        VERSION:     '0.1.2',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true,
        SOURCELINK_SUFFIX: '.txt'
      };
    </script>
    <script type="text/javascript" src="../../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../../_static/doctools.js"></script>
    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" /> 
  </head>
  <body role="document">
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../../../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../../../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="nav-item nav-item-0"><a href="../../../index.html">pgmpy 0.1.2 documentation</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="../../index.html" accesskey="U">Module code</a> &#187;</li> 
      </ul>
    </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
            <p class="logo"><a href="../../../index.html">
              <img class="logo" src="../../../_static/logo.png" alt="Logo"/>
            </a></p>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <form class="search" action="../../../search.html" method="get">
      <div><input type="text" name="q" /></div>
      <div><input type="submit" value="Go" /></div>
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <h1>Source code for pgmpy.estimators.BayesianEstimator</h1><div class="highlight"><pre>
<span></span><span class="c1"># -*- coding: utf-8 -*-</span>

<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>

<span class="kn">from</span> <span class="nn">pgmpy.estimators</span> <span class="k">import</span> <span class="n">ParameterEstimator</span>
<span class="kn">from</span> <span class="nn">pgmpy.factors.discrete</span> <span class="k">import</span> <span class="n">TabularCPD</span>
<span class="kn">from</span> <span class="nn">pgmpy.models</span> <span class="k">import</span> <span class="n">BayesianModel</span>


<div class="viewcode-block" id="BayesianEstimator"><a class="viewcode-back" href="../../../estimators.html#pgmpy.estimators.BayesianEstimator.BayesianEstimator">[docs]</a><span class="k">class</span> <span class="nc">BayesianEstimator</span><span class="p">(</span><span class="n">ParameterEstimator</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">model</span><span class="p">,</span> <span class="n">data</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Class used to compute parameters for a model using Bayesian Parameter Estimation.</span>
<span class="sd">        See `MaximumLikelihoodEstimator` for constructor parameters.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">BayesianModel</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">NotImplementedError</span><span class="p">(</span><span class="s2">&quot;Bayesian Parameter Estimation is only implemented for BayesianModel&quot;</span><span class="p">)</span>

        <span class="nb">super</span><span class="p">(</span><span class="n">BayesianEstimator</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">data</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

<div class="viewcode-block" id="BayesianEstimator.get_parameters"><a class="viewcode-back" href="../../../estimators.html#pgmpy.estimators.BayesianEstimator.BayesianEstimator.get_parameters">[docs]</a>    <span class="k">def</span> <span class="nf">get_parameters</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">prior_type</span><span class="o">=</span><span class="s1">&#39;BDeu&#39;</span><span class="p">,</span> <span class="n">equivalent_sample_size</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">pseudo_counts</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Method to estimate the model parameters (CPDs).</span>

<span class="sd">        Parameters</span>
<span class="sd">        ----------</span>
<span class="sd">        prior_type: &#39;dirichlet&#39;, &#39;BDeu&#39;, or &#39;K2&#39;</span>
<span class="sd">            string indicting which type of prior to use for the model parameters.</span>
<span class="sd">            - If &#39;prior_type&#39; is &#39;dirichlet&#39;, the following must be provided:</span>
<span class="sd">                &#39;pseudo_counts&#39; = dirichlet hyperparameters; a dict containing, for each variable, a list</span>
<span class="sd">                 with a &quot;virtual&quot; count for each variable state, that is added to the state counts.</span>
<span class="sd">                 (lexicographic ordering of states assumed)</span>
<span class="sd">            - If &#39;prior_type&#39; is &#39;BDeu&#39;, then an &#39;equivalent_sample_size&#39;</span>
<span class="sd">                must be specified instead of &#39;pseudo_counts&#39;. This is equivalent to</span>
<span class="sd">                &#39;prior_type=dirichlet&#39; and using uniform &#39;pseudo_counts&#39; of</span>
<span class="sd">                `equivalent_sample_size/(node_cardinality*np.prod(parents_cardinalities))` for each node.</span>
<span class="sd">                &#39;equivalent_sample_size&#39; can either be a numerical value or a dict that specifies</span>
<span class="sd">                the size for each variable seperately.</span>
<span class="sd">            - A prior_type of &#39;K2&#39; is a shorthand for &#39;dirichlet&#39; + setting every pseudo_count to 1,</span>
<span class="sd">                regardless of the cardinality of the variable.</span>

<span class="sd">        Returns</span>
<span class="sd">        -------</span>
<span class="sd">        parameters: list</span>
<span class="sd">            List of TabularCPDs, one for each variable of the model</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        &gt;&gt;&gt; import numpy as np</span>
<span class="sd">        &gt;&gt;&gt; import pandas as pd</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.models import BayesianModel</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.estimators import BayesianEstimator</span>
<span class="sd">        &gt;&gt;&gt; values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 4)),</span>
<span class="sd">        ...                       columns=[&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;])</span>
<span class="sd">        &gt;&gt;&gt; model = BayesianModel([(&#39;A&#39;, &#39;B&#39;), (&#39;C&#39;, &#39;B&#39;), (&#39;C&#39;, &#39;D&#39;)])</span>
<span class="sd">        &gt;&gt;&gt; estimator = BayesianEstimator(model, values)</span>
<span class="sd">        &gt;&gt;&gt; estimator.get_parameters(prior_type=&#39;BDeu&#39;, equivalent_sample_size=5)</span>
<span class="sd">        [&lt;TabularCPD representing P(C:2) at 0x7f7b534251d0&gt;,</span>
<span class="sd">        &lt;TabularCPD representing P(B:2 | C:2, A:2) at 0x7f7b4dfd4da0&gt;,</span>
<span class="sd">        &lt;TabularCPD representing P(A:2) at 0x7f7b4dfd4fd0&gt;,</span>
<span class="sd">        &lt;TabularCPD representing P(D:2 | C:2) at 0x7f7b4df822b0&gt;]</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">parameters</span> <span class="o">=</span> <span class="p">[]</span>

        <span class="k">for</span> <span class="n">node</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">nodes</span><span class="p">():</span>
            <span class="n">_equivalent_sample_size</span> <span class="o">=</span> <span class="n">equivalent_sample_size</span><span class="p">[</span><span class="n">node</span><span class="p">]</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">equivalent_sample_size</span><span class="p">,</span> <span class="nb">dict</span><span class="p">)</span> <span class="k">else</span> \
                                      <span class="n">equivalent_sample_size</span>
            <span class="n">_pseudo_counts</span> <span class="o">=</span> <span class="n">pseudo_counts</span><span class="p">[</span><span class="n">node</span><span class="p">]</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">pseudo_counts</span><span class="p">,</span> <span class="nb">dict</span><span class="p">)</span> <span class="k">else</span> <span class="n">pseudo_counts</span>

            <span class="n">cpd</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">estimate_cpd</span><span class="p">(</span><span class="n">node</span><span class="p">,</span>
                                    <span class="n">prior_type</span><span class="o">=</span><span class="n">prior_type</span><span class="p">,</span>
                                    <span class="n">equivalent_sample_size</span><span class="o">=</span><span class="n">_equivalent_sample_size</span><span class="p">,</span>
                                    <span class="n">pseudo_counts</span><span class="o">=</span><span class="n">_pseudo_counts</span><span class="p">)</span>
            <span class="n">parameters</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">cpd</span><span class="p">)</span>

        <span class="k">return</span> <span class="n">parameters</span></div>

<div class="viewcode-block" id="BayesianEstimator.estimate_cpd"><a class="viewcode-back" href="../../../estimators.html#pgmpy.estimators.BayesianEstimator.BayesianEstimator.estimate_cpd">[docs]</a>    <span class="k">def</span> <span class="nf">estimate_cpd</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">node</span><span class="p">,</span> <span class="n">prior_type</span><span class="o">=</span><span class="s1">&#39;BDeu&#39;</span><span class="p">,</span> <span class="n">pseudo_counts</span><span class="o">=</span><span class="p">[],</span> <span class="n">equivalent_sample_size</span><span class="o">=</span><span class="mi">5</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Method to estimate the CPD for a given variable.</span>

<span class="sd">        Parameters</span>
<span class="sd">        ----------</span>
<span class="sd">        node: int, string (any hashable python object)</span>
<span class="sd">            The name of the variable for which the CPD is to be estimated.</span>

<span class="sd">        prior_type: &#39;dirichlet&#39;, &#39;BDeu&#39;, &#39;K2&#39;,</span>
<span class="sd">            string indicting which type of prior to use for the model parameters.</span>
<span class="sd">            - If &#39;prior_type&#39; is &#39;dirichlet&#39;, the following must be provided:</span>
<span class="sd">                &#39;pseudo_counts&#39; = dirichlet hyperparameters; a list or dict</span>
<span class="sd">                 with a &quot;virtual&quot; count for each variable state.</span>
<span class="sd">                 The virtual counts are added to the actual state counts found in the data.</span>
<span class="sd">                 (if a list is provided, a lexicographic ordering of states is assumed)</span>
<span class="sd">            - If &#39;prior_type&#39; is &#39;BDeu&#39;, then an &#39;equivalent_sample_size&#39;</span>
<span class="sd">                must be specified instead of &#39;pseudo_counts&#39;. This is equivalent to</span>
<span class="sd">                &#39;prior_type=dirichlet&#39; and using uniform &#39;pseudo_counts&#39; of</span>
<span class="sd">                `equivalent_sample_size/(node_cardinality*np.prod(parents_cardinalities))`.</span>
<span class="sd">            - A prior_type of &#39;K2&#39; is a shorthand for &#39;dirichlet&#39; + setting every pseudo_count to 1,</span>
<span class="sd">                regardless of the cardinality of the variable.</span>

<span class="sd">        Returns</span>
<span class="sd">        -------</span>
<span class="sd">        CPD: TabularCPD</span>

<span class="sd">        Examples</span>
<span class="sd">        --------</span>
<span class="sd">        &gt;&gt;&gt; import pandas as pd</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.models import BayesianModel</span>
<span class="sd">        &gt;&gt;&gt; from pgmpy.estimators import BayesianEstimator</span>
<span class="sd">        &gt;&gt;&gt; data = pd.DataFrame(data={&#39;A&#39;: [0, 0, 1], &#39;B&#39;: [0, 1, 0], &#39;C&#39;: [1, 1, 0]})</span>
<span class="sd">        &gt;&gt;&gt; model = BayesianModel([(&#39;A&#39;, &#39;C&#39;), (&#39;B&#39;, &#39;C&#39;)])</span>
<span class="sd">        &gt;&gt;&gt; estimator = BayesianEstimator(model, data)</span>
<span class="sd">        &gt;&gt;&gt; cpd_C = estimator.estimate_cpd(&#39;C&#39;, prior_type=&quot;dirichlet&quot;, pseudo_counts=[1, 2])</span>
<span class="sd">        &gt;&gt;&gt; print(cpd_C)</span>
<span class="sd">        ╒══════╤══════╤══════╤══════╤════════════════════╕</span>
<span class="sd">        │ A    │ A(0) │ A(0) │ A(1) │ A(1)               │</span>
<span class="sd">        ├──────┼──────┼──────┼──────┼────────────────────┤</span>
<span class="sd">        │ B    │ B(0) │ B(1) │ B(0) │ B(1)               │</span>
<span class="sd">        ├──────┼──────┼──────┼──────┼────────────────────┤</span>
<span class="sd">        │ C(0) │ 0.25 │ 0.25 │ 0.5  │ 0.3333333333333333 │</span>
<span class="sd">        ├──────┼──────┼──────┼──────┼────────────────────┤</span>
<span class="sd">        │ C(1) │ 0.75 │ 0.75 │ 0.5  │ 0.6666666666666666 │</span>
<span class="sd">        ╘══════╧══════╧══════╧══════╧════════════════════╛</span>
<span class="sd">        &quot;&quot;&quot;</span>

        <span class="n">node_cardinality</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">state_names</span><span class="p">[</span><span class="n">node</span><span class="p">])</span>
        <span class="n">parents</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">get_parents</span><span class="p">(</span><span class="n">node</span><span class="p">))</span>
        <span class="n">parents_cardinalities</span> <span class="o">=</span> <span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">state_names</span><span class="p">[</span><span class="n">parent</span><span class="p">])</span> <span class="k">for</span> <span class="n">parent</span> <span class="ow">in</span> <span class="n">parents</span><span class="p">]</span>

        <span class="k">if</span> <span class="n">prior_type</span> <span class="o">==</span> <span class="s1">&#39;K2&#39;</span><span class="p">:</span>
            <span class="n">pseudo_counts</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">*</span> <span class="n">node_cardinality</span>
        <span class="k">elif</span> <span class="n">prior_type</span> <span class="o">==</span> <span class="s1">&#39;BDeu&#39;</span><span class="p">:</span>
            <span class="n">alpha</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">equivalent_sample_size</span><span class="p">)</span> <span class="o">/</span> <span class="p">(</span><span class="n">node_cardinality</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">prod</span><span class="p">(</span><span class="n">parents_cardinalities</span><span class="p">))</span>
            <span class="n">pseudo_counts</span> <span class="o">=</span> <span class="p">[</span><span class="n">alpha</span><span class="p">]</span> <span class="o">*</span> <span class="n">node_cardinality</span>
        <span class="k">elif</span> <span class="n">prior_type</span> <span class="o">==</span> <span class="s1">&#39;dirichlet&#39;</span><span class="p">:</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="nb">len</span><span class="p">(</span><span class="n">pseudo_counts</span><span class="p">)</span> <span class="o">==</span> <span class="n">node_cardinality</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;&#39;pseudo_counts&#39; should have length </span><span class="si">{0}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">node_cardinality</span><span class="p">))</span>
            <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">pseudo_counts</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span>
                <span class="n">pseudo_counts</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">pseudo_counts</span><span class="o">.</span><span class="n">values</span><span class="p">())</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;&#39;prior_type&#39; not specified&quot;</span><span class="p">)</span>

        <span class="n">state_counts</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">state_counts</span><span class="p">(</span><span class="n">node</span><span class="p">)</span>
        <span class="n">bayesian_counts</span> <span class="o">=</span> <span class="p">(</span><span class="n">state_counts</span><span class="o">.</span><span class="n">T</span> <span class="o">+</span> <span class="n">pseudo_counts</span><span class="p">)</span><span class="o">.</span><span class="n">T</span>

        <span class="n">cpd</span> <span class="o">=</span> <span class="n">TabularCPD</span><span class="p">(</span><span class="n">node</span><span class="p">,</span> <span class="n">node_cardinality</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">bayesian_counts</span><span class="p">),</span>
                         <span class="n">evidence</span><span class="o">=</span><span class="n">parents</span><span class="p">,</span>
                         <span class="n">evidence_card</span><span class="o">=</span><span class="n">parents_cardinalities</span><span class="p">,</span>
                         <span class="n">state_names</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">state_names</span><span class="p">)</span>
        <span class="n">cpd</span><span class="o">.</span><span class="n">normalize</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">cpd</span></div></div>
</pre></div>

          </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../../../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../../../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="nav-item nav-item-0"><a href="../../../index.html">pgmpy 0.1.2 documentation</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="../../index.html" >Module code</a> &#187;</li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &#169; Copyright 2016, Ankur Ankan.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.5.1.
    </div>
  </body>
</html>